package com.example.demo.demos.web.controller;

import com.example.demo.demos.web.dto.TextToSpeechDTO;
import com.example.demo.demos.web.result.Result;
import com.example.demo.demos.web.service.TextToSpeechService;
import com.example.demo.demos.web.vo.TextToSpeechVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;

@RestController
@RequestMapping("/api")
public class TextToSpeechController {

    private final TextToSpeechService textToSpeechService;

    public TextToSpeechController(TextToSpeechService textToSpeechService) {
        this.textToSpeechService = textToSpeechService;
    }

    @PostMapping("/stream")
    public Result<TextToSpeechVO> textToSpeech(@RequestBody TextToSpeechDTO textToSpeechDTO){
        try {
            byte[] speechStream = textToSpeechService.convertTextToSpeechStream(textToSpeechDTO);
            System.out.println(textToSpeechDTO.getText());

            String resourcePath = new File("src/main/resources/static/video").getAbsolutePath();
            Random random = new Random();
            int num = random.nextInt(100) + 1;
            String fileName = "output" + num + ".wav";
            try (FileOutputStream fos = new FileOutputStream(resourcePath + "/" + fileName)) {
                fos.write(speechStream);
            }
            TextToSpeechVO vo = TextToSpeechVO.builder()
                    .sourceIP(textToSpeechDTO.getSourceIP())
                    .destinationIP(textToSpeechDTO.getDestinationIP())
                    .streamData(speechStream)
                    .build();
            return Result.success(vo);
        } catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/test")
    public Result<String> test(@RequestBody TextToSpeechDTO textToSpeechDTO){
        return Result.success(textToSpeechDTO.getText());
    }
}
